﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Subsidiary.BookSearch
{
    class Analysis
    {
        static string pattern = @"<a.+href=""([^""]*)""[^>]+><img.+src=""([^""]*)""[^>]+></a>";
        static string authorPattern = @"<span class=""med reg"">(.*)\s(\(\d{4}\-\d{2}[^\)]*\))</span>";
        static string contentPattern = @"<div.*id=""postBodyPS""[^>]*>\s*<div>(.*)</div>\s*</div>";
        static string titlePattern = @"<span.*id=""btAsinTitle"">(.*)<span.*[^>]>";
        public BookItem PickupSearch(BookItem book, string html, ref string urlOfDetail, ref string urlOfPicture)
        {
            if (string.IsNullOrEmpty(html))
            {
                return book;
            }
            html = html.Trim();
            if (html.Length == 0)
            {
                return book;
            }
            book.Name = string.Empty;
            int posOfResult0 = html.IndexOf("<div id=\"result_0\"");
            if (posOfResult0 > 0)
            {
                int posOfltL = html.IndexOf("<ul class=\"rsltL\">", posOfResult0);
                if (posOfltL > 0)
                {
                    html = html.Substring(posOfResult0, posOfltL - posOfResult0);
                    Match m = Regex.Match(html, pattern);
                    if (m.Success)
                    {
                        urlOfDetail = m.Groups[1].Value;
                        urlOfPicture = m.Groups[2].Value;
                    }

                    Match authoMatch = Regex.Match(html, authorPattern);
                    if (authoMatch.Success)
                    {
                        int posOfSpace = authoMatch.Groups[1].Value.LastIndexOf(" ");
                        if (posOfSpace > 0)
                        {
                            book.Author = authoMatch.Groups[1].Value.Substring(0, posOfSpace);
                            book.Publishing = authoMatch.Groups[1].Value.Substring(posOfSpace + 1);
                        }

                    }
                }
            }
            return book;
        }

        public BookItem PickupDetail(BookItem book, string html)
        {
            Match titleMatch = Regex.Match(html, titlePattern);
            if (titleMatch.Success)
            {
                book.Name = titleMatch.Groups[1].Value;
            }

            Match contentMatch = Regex.Match(html, contentPattern);
            if (contentMatch.Success)
            {
                book.Summary = contentMatch.Groups[1].Value;
            }
            return book;
        }

    }
}
